﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;

namespace FFmpegVideoClip
{
    public class TextBoxTextChangedLimit
    {

        protected Dictionary<TextBox, string> controls = new Dictionary<TextBox, string>();

        public event Action<TextBox, string>? TextChanged;

        public bool EnableTextChangedEvent = true;

        public virtual void RegisterControl(TextBox control)
        {
            if (controls.ContainsKey(control))
                return;
            controls.Add(control, string.Empty);
            control.PreviewMouseDown += Control_PreviewMouseDown;
            control.TextChanged += Control_TextChanged;
        }

        public virtual void UnRegisterControl(TextBox control)
        {
            if (!controls.ContainsKey(control))
                return;
            controls.Remove(control);
            control.PreviewMouseDown -= Control_PreviewMouseDown;
            control.TextChanged -= Control_TextChanged;
        }

        public void SetHistoryValue(TextBox textBox, string Value)
        {
            if (!controls.ContainsKey(textBox))
                throw new TextBoxInstanceNoRegisterException();
            controls[textBox] = Value;
        }

        protected void Control_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox obj = (TextBox)sender;
            string text = controls[obj];
            if (EnableTextChangedEvent)
                TextChanged?.Invoke(obj, text);
            if (!obj.Text.Equals(text, StringComparison.Ordinal))
                controls[obj] = obj.Text;
        }

        protected void Control_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 3)
                ((TextBox)sender).SelectAll();
        }


        [Serializable]
        public class TextBoxInstanceNoRegisterException : Exception
        {
            public TextBoxInstanceNoRegisterException() : base("当前TextBox未注册") { }
            public TextBoxInstanceNoRegisterException(Exception inner) : base("当前TextBox未注册", inner) { }
        }
    }
}
